package com.qijia.travel.app;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.qijia.travel.common.Constants;
import com.qijia.travel.common.SqlMappedId;
import com.qijia.travel.dao.BaseDAO;
import com.qijia.travel.dao.SingletonDaoFactory;
import com.qijia.travel.dao.TravelDbException;
import com.qijia.travel.domain.Guide;
import com.qijia.travel.domain.GuideAccount;
import com.qijia.travel.domain.GuideStatus;
import com.qijia.travel.domain.PageResult;
import com.qijia.travel.domain.TouristGroupDetail;
import com.qijia.travel.domain.TreamGuide;
import com.qijia.travel.domain.example.ExampleFactory;
import com.qijia.travel.domain.example.GuideAccountExample;
import com.qijia.travel.domain.example.GuideExample;
import com.qijia.travel.domain.example.GuideStatusExample;
import com.qijia.travel.domain.example.TreamGuideExample;
import com.qijia.travel.helper.DateHelper;
import com.qijia.travel.helper.ObjectHelper;
import com.qijia.travel.vo.GuideVO;

public class GuideManager {

	private BaseDAO baseDao;
	private StatusManager statusManager;

	public GuideManager() {
		try {
			baseDao = SingletonDaoFactory.createDAO();
			statusManager = new StatusManager();
		} catch (TravelDbException e) {
			e.printStackTrace();
		}
	}

	public Guide settingGuide(Guide guide) throws AppErrorException {
		if (guide == null)
			return null;
		try {
			if (guide.getGuideId() != null && guide.getGuideId() != 0) {// Id不为空
				Guide otherGuide = getGuideById(guide.getGuideId());
				if (otherGuide == null || otherGuide.getGuideName() == null) {// 查询不到该导游
					guide.setGuideSex("1");
					guide.setGuideType(2);
					this.createGuide(guide);
					return guide;
				} else
					return otherGuide;
			} else if (guide.getGuideName() != null
					&& guide.getGuideName().trim().length() > 0) {// 名字不为空
				Guide otherGuide = getGuideByName(guide.getGuideName());
				if (otherGuide == null || otherGuide.getGuideName() == null) {// 查询不到该导游
					guide.setGuideSex("1");
					guide.setGuideType(2);
					guide.setGuideId(createGuide(guide));
					return guide;
				} else
					return otherGuide;
			} else
				return null;
		} catch (AppErrorException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public Guide login(String accountName, String password)
			throws AppErrorException {
		if (accountName == null || password == null)
			throw new AppErrorException("用户名或密码不能为空!");

		GuideAccountExample example = ExampleFactory
				.createGuideAccountExample();
		GuideAccountExample.Criteria cr = example.createCriteria();

		cr.andAccountNameEqualTo(accountName);
		try {
			if (baseDao.countByExample(SqlMappedId.GUIDE_ACCOUNT + "."
					+ SqlMappedId.countByExample, example) > 0) {
				GuideAccount account = (GuideAccount) baseDao.selectByExample(
						SqlMappedId.GUIDE_ACCOUNT + "."
								+ SqlMappedId.selectByExample, example).get(0);

				if (account.getPassword() == null)
					throw new AppErrorException("账户密码非法设置错误!");

				if (account.getPassword().equals(password)) {
					Guide guide = this.getGuideById(account.getGuideId());
					Date loginDate = guide.getLoginDate();
					guide.setLoginDate(new Date());
					updateGuide(guide);

					guide.setLoginDate(loginDate);
					return guide;
				} else
					throw new AppErrorException("用户名或密码错误!");
			} else
				throw new AppErrorException("不存在此用户名!");
		} catch (TravelDbException e) {
			throw new AppErrorException("登录失败,请稍候重试!");
		}
	}

	public String createAccount(GuideAccount account) {
		if (account == null || account.getGuideId() == null)
			return "创建账号失败[请正确输入登录账号]!";
		else if (account.getAccountName() == null
				|| account.getPassword() == null) {
			return "创建账号失败[登录账号或密码不能为空]!";
		}
		GuideAccount accountOld = getAccountInfo(account.getGuideId());
		if (accountOld == null) {// 账号不存在
			try {
				this.baseDao.insert(SqlMappedId.GUIDE_ACCOUNT + "."
						+ SqlMappedId.insert, account);
				return "创建账号成功!";
			} catch (TravelDbException e) {
				e.printStackTrace();
				return "创建账号失败!";
			}

		} else {
			account.setAccountId(accountOld.getAccountId());
			account.setAccountName(accountOld.getAccountName());// 不能修改账号名

			try {
				this.baseDao.updateByPrimaryKeySelective(
						SqlMappedId.GUIDE_ACCOUNT + "."
								+ SqlMappedId.updateByPrimaryKeySelective,
						account);
				return "修改账号密码成功!";
			} catch (TravelDbException e) {
				e.printStackTrace();
				return "创建账号失败!";
			}
		}
	}

	public GuideAccount getAccountInfo(Integer guideId) {
		GuideAccountExample example = ExampleFactory
				.createGuideAccountExample();
		GuideAccountExample.Criteria cr = example.createCriteria();

		cr.andGuideIdEqualTo(guideId);

		try {
			List<?> datas = baseDao.selectByExample(SqlMappedId.GUIDE_ACCOUNT
					+ "." + SqlMappedId.selectByExample, example);

			if (datas != null && datas.size() > 0)
				return (GuideAccount) datas.get(0);
			else
				return null;
		} catch (TravelDbException e) {
			e.printStackTrace();
		}

		return null;
	}

	public Guide getGuideById(int guideId) throws AppErrorException {
		Guide guide = new Guide();
		guide.setGuideId(guideId);

		try {
			return (Guide) baseDao.selectByPrimaryKey(SqlMappedId.GUIDE + "."
					+ SqlMappedId.selectByPrimaryKey, guide);
		} catch (TravelDbException e) {
			throw new AppErrorException("获取导游基本信息失败!");
		}
	}

	@SuppressWarnings("unchecked")
	public Guide getGuideByName(String guideName) throws AppErrorException {
		GuideExample example = ExampleFactory.createGuideExample();
		GuideExample.Criteria cr = example.createCriteria(null);
		cr.andGuideNameEqualTo(guideName);

		try {
			if (baseDao.countByExample(SqlMappedId.GUIDE + "."
					+ SqlMappedId.countByExample, example) > 1) {
				throw new AppErrorException("该导游[" + guideName
						+ "]存在同名,请指定其ID号!");
			} else if (baseDao.countByExample(SqlMappedId.GUIDE + "."
					+ SqlMappedId.countByExample, example) == 1) {
				example.setPageSize(1);
				List<Guide> guides = (List<Guide>) baseDao.selectByExample(
						SqlMappedId.GUIDE + "." + SqlMappedId.selectByExample,
						example);

				return guides.size() > 0 ? guides.get(0) : null;
			} else
				return null;
		} catch (TravelDbException e) {
			e.printStackTrace();
			throw new AppErrorException("获取导游基本信息失败!", e);
		}
	}

	public void updatePwd(String oldPwd, String pwd, HttpSession session)
			throws AppErrorException {
		Guide guide = (Guide) session.getAttribute(Constants.USER_KEY);

		if (guide == null)
			throw new AppErrorException("请先登录吧!");

		GuideAccount account = this.getAccountInfo(guide.getGuideId());
		if (account == null) {
			throw new AppErrorException("你不存在登录账号，请联系管理员为你创建一个登录账号!");
		}
		if (oldPwd.equals(account.getPassword())) {
			account.setPassword(pwd);

			try {
				this.baseDao.updateByPrimaryKeySelective(
						SqlMappedId.GUIDE_ACCOUNT + "."
								+ SqlMappedId.updateByPrimaryKeySelective,
						account);
			} catch (TravelDbException e) {
				throw new AppErrorException("修改密码失败，请稍候重试!");
			}
		} else
			throw new AppErrorException("请输入正确的原密码!");
	}

	@SuppressWarnings("unchecked")
	public void saveGuideToTream(int guideId, int treamId)
			throws TravelDbException {

		TreamGuideExample example = ExampleFactory.createTreamGuideExample();
		TreamGuideExample.Criteria cr = example.createCriteria();
		cr.andTgGuideIdEqualTo(guideId);

		if (baseDao.countByExample(SqlMappedId.TREAM_GUIDE + "."
				+ SqlMappedId.countByExample, example) > 0) {// 其导游已处于团队中
			cr.andTgTreamIdEqualTo(treamId);
			if (baseDao.countByExample(SqlMappedId.TREAM_GUIDE + "."
					+ SqlMappedId.countByExample, example) <= 0) {// 若其不处于选中的团队，则进行修改操作

				example.clear();
				example.createCriteria().andTgGuideIdEqualTo(guideId);
				List<TreamGuide> treamGuides = (List<TreamGuide>) baseDao
						.selectByExample(SqlMappedId.TREAM_GUIDE + "."
								+ SqlMappedId.selectByExample, example);

				TreamGuide treamGuide = new TreamGuide();
				treamGuide
						.setTreamGuideId(treamGuides.get(0).getTreamGuideId());
				treamGuide.setGuideId(guideId);
				treamGuide.setTreamId(treamId);

				baseDao.updateByPrimaryKeySelective(SqlMappedId.TREAM_GUIDE
						+ "." + SqlMappedId.updateByPrimaryKeySelective,
						treamGuide);
			}
		} else {// 若其不处在任何团队，则新注册
			TreamGuide treamGuide = new TreamGuide();
			treamGuide.setGuideId(guideId);
			treamGuide.setTreamId(treamId);
			baseDao.insert(SqlMappedId.TREAM_GUIDE + "." + SqlMappedId.insert,
					treamGuide);
		}
	}

	@SuppressWarnings("unchecked")
	public GuideStatus getGuideStatus(int guideId) throws AppErrorException {
		if (guideId <= 0)
			return null;
		GuideStatusExample example = ExampleFactory.createGuideStatusExample();
		GuideStatusExample.Criteria cr = example.createCriteria();
		cr.andGsGuideIdEqualTo(guideId);

		try {
			if (baseDao.countByExample(SqlMappedId.GUIDE_STATUS + "."
					+ SqlMappedId.countByExample, example) > 0) {// 其导游已处于该状态中
				return (GuideStatus) baseDao.selectByExample(
						SqlMappedId.GUIDE_STATUS + "."
								+ SqlMappedId.selectByExample, example).get(0);
			} else
				return null;
		} catch (TravelDbException e) {
			e.printStackTrace();
			throw new AppErrorException("获取导游状态失败!");
		}
	}

	public void updateGuideStatus(final TouristGroupDetail detail)
			throws AppErrorException {
		if (detail!=null && detail.getStartDt() != null && detail.getEndDt() != null) {
			Date rightNow = new Date();
			if (rightNow.after(detail.getStartDt())
					&& rightNow.before(detail.getEndDt())) {
				saveGuideToStatus(detail.getGuideId(), Constants.LIVE_STATUS);
			} else if (rightNow.before(detail.getStartDt())) {// 若未到此时间则显示为已预订
				saveGuideToStatus(detail.getGuideId(), Constants.READY_STATUS);
			} else {
				GuideStatus status = getGuideStatus(detail.getGuideId());
				if (status != null) {
					if (Constants.OFF_STATUS != status.getStatusId())// 如果该导游的状态不为请假状态
						saveGuideToStatus(detail.getGuideId(),
								Constants.ON_STATUS);
				} else
					saveGuideToStatus(detail.getGuideId(), Constants.ON_STATUS);
			}
		}
	}

	public void updateGuideStatus(int guideId, String startDate, String endDate)
			throws AppErrorException {
		TouristGroupDetail detail = new TouristGroupDetail();
		detail.setGuideId(guideId);

		if (startDate != null && startDate.trim().length() > 0)
			detail.setStartDt(DateHelper.parseToDate(startDate,
					DateHelper.yyyyMMdd));

		if (endDate != null && endDate.trim().length() > 0){//应包括今天
			Calendar cal = Calendar.getInstance();
			
			cal.setTime(DateHelper
					.parseToDate(endDate, DateHelper.yyyyMMdd));
			cal.add(Calendar.DATE, 1);
			detail.setEndDt(cal.getTime());
		}
		
		updateGuideStatus(detail);
	}

	@SuppressWarnings("unchecked")
	public void saveGuideToStatus(int guideId, int statusId)
			throws AppErrorException {

		GuideStatusExample example = ExampleFactory.createGuideStatusExample();
		GuideStatusExample.Criteria cr = example.createCriteria();
		cr.andGsGuideIdEqualTo(guideId);

		try {
			if (baseDao.countByExample(SqlMappedId.GUIDE_STATUS + "."
					+ SqlMappedId.countByExample, example) > 0) {// 其导游已处于该状态中
				cr.andGsStatusIdEqualTo(statusId);
				if (baseDao.countByExample(SqlMappedId.GUIDE_STATUS + "."
						+ SqlMappedId.countByExample, example) <= 0) {// 若其不处于选中的状态，则进行修改操作

					example.clear();
					example.createCriteria().andGsGuideIdEqualTo(guideId);
					List<GuideStatus> guidesStatus = (List<GuideStatus>) baseDao
							.selectByExample(SqlMappedId.GUIDE_STATUS + "."
									+ SqlMappedId.selectByExample, example);

					GuideStatus guideStatus = new GuideStatus();
					guideStatus.setGuideStatusId(guidesStatus.get(0)
							.getGuideStatusId());
					guideStatus.setGuideId(guideId);
					guideStatus.setStatusId(statusId);
					guideStatus.setLastStatusId(guidesStatus.get(0)
							.getStatusId());
					guideStatus.setGuideName(getGuideById(guideId)
							.getGuideName());
					guideStatus.setStatusName(statusManager.getStatusById(
							statusId).getStatusName());

					baseDao.updateByPrimaryKeySelective(
							SqlMappedId.GUIDE_STATUS + "."
									+ SqlMappedId.updateByPrimaryKeySelective,
							guideStatus);
				}
			} else {// 若其不处在任何团队，则新注册
				GuideStatus guideStatus = new GuideStatus();
				guideStatus.setGuideId(guideId);
				guideStatus.setStatusId(statusId);
				guideStatus.setGuideName(getGuideById(guideId).getGuideName());
				guideStatus.setStatusName(statusManager.getStatusById(statusId)
						.getStatusName());
				baseDao.insert(SqlMappedId.GUIDE_STATUS + "."
						+ SqlMappedId.insert, guideStatus);
			}
		} catch (TravelDbException e) {
			throw new AppErrorException("保存导游状态发生错误,请稍候重试!", e);
		}
	}

	public int createGuide(Guide guide) throws AppErrorException {
		if (guide == null)
			throw new AppErrorException("请输入新增的导游的基本信息");
		try {
			guide.setGuideId(baseDao.getAutoIncrementId(SqlMappedId.GUIDE));
			baseDao.insert(SqlMappedId.GUIDE + "." + SqlMappedId.insert, guide);
			return guide.getGuideId();
		} catch (TravelDbException e) {
			throw new AppErrorException("注册新导游失败,请稍候重试!", e);
		}
	}

	public void updateGuide(Guide guide) throws AppErrorException {
		if (guide == null)
			throw new AppErrorException("请选择要进行修改的导游");
		try {
			baseDao.updateByPrimaryKeySelective(SqlMappedId.GUIDE + "."
					+ SqlMappedId.updateByPrimaryKeySelective, guide);
		} catch (TravelDbException e) {
			throw new AppErrorException("更新选中的导游[" + guide.getGuideName()
					+ "]失败,请稍候重试!", e);
		}
	}

	public void deleteGuide(int guideId) throws AppErrorException {
		if (guideId == 0)
			throw new AppErrorException("请选择要进行删除的导游");
		Guide guide = new Guide();
		try {
			guide.setGuideId(guideId);
			baseDao.deleteByPrimaryKey(SqlMappedId.GUIDE + "."
					+ SqlMappedId.deleteByPrimaryKey, guide);
		} catch (TravelDbException e) {
			throw new AppErrorException("删除选中的导游[编号为:" + guide.getGuideId()
					+ "]失败,请稍候重试!", e);
		}
	}

	public void deleteGuides(String guideIds) throws AppErrorException {
		if (guideIds == null)
			throw new AppErrorException("请选择要进行删除的导游");

		if (guideIds.indexOf(",") > 0) {
			for (String guideId : guideIds.split(",")) {
				try {
					this.deleteGuide(Integer.parseInt(guideId));
				} catch (NumberFormatException e) {

				}
			}
		} else {
			try {
				this.deleteGuide(Integer.parseInt(guideIds));
			} catch (NumberFormatException e) {
				throw new AppErrorException("请选择要进行删除的导游");
			}
		}
	}

	public PageResult selectGuideList(GuideVO guide) throws AppErrorException {

		GuideExample example = ExampleFactory.createGuideExample();
		example.createCriteria(guide);

		if (guide.getOrderBy() == null
				|| guide.getOrderBy().trim().length() <= 0)
			example.setOrderByClause(" guide_seq, reg_date desc ");
		else {
			try {
				example.setOrderByClause(ObjectHelper.getOrderBy(guide
						.getOrderBy(), guide.getACode() == null ? 0 : guide
						.getACode()));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		try {
			PageResult page = PageResult.newInstance();
			page.setSelectDataMappedId(SqlMappedId.GUIDE + "."
					+ SqlMappedId.selectByExample);
			page.setCountMappedId(SqlMappedId.GUIDE + "."
					+ SqlMappedId.countByExample);
			page.setSqlParamObj(example);

			if (guide.getCurPage() == null || guide.getCurPage() == 0
					|| guide.getCurPage() <= 1) {
				page.setCurPage(1);
			} else {
				page.setCurPage(guide.getCurPage());
			}
			page.setPageSize(20);

			return baseDao.selectByPage(page);
		} catch (TravelDbException e) {
			throw new AppErrorException("获取导游数据列表失败,请稍候重试!", e);
		} catch (InstantiationException e) {
			throw new AppErrorException("获取导游数据列表失败,请稍候重试!", e);
		} catch (IllegalAccessException e) {
			throw new AppErrorException("获取导游数据列表失败,请稍候重试!", e);
		}
	}

}
